from flask import Flask, render_template, Response, jsonify
import io
import time
from threading import Condition
import logging

app = Flask(__name__)

# log = logging.getLogger('werkzeug')
# log.setLevel(logging.ERROR)
# app.debug = True # 开关终端日志

# ----------------- 视频流 -----------------
class StreamingOutput(object):
    def __init__(self):
        self.frame = None
        self.buffer = io.BytesIO()
        self.condition = Condition()

    def write(self, buf):
        if buf.startswith(b'\xff\xd8'):
            self.buffer.truncate()
            with self.condition:
                self.frame = self.buffer.getvalue()
                self.condition.notify_all()
            self.buffer.seek(0)
        return self.buffer.write(buf)

output = StreamingOutput()

def gen():
    """MJPEG 帧生成器"""
    while True:
        with output.condition:
            output.condition.wait()
            frame = output.frame
        yield (b'--frame\r\n'b'Content-Type: image/jpeg\r\n\r\n' + frame + b'\r\n')

@app.route('/video')
def video_feed():
    return Response(gen(), mimetype='multipart/x-mixed-replace; boundary=frame')

# ----------------- 数据接口 -----------------
@app.route('/data')
def data():
    # 这里只是 mock，真实可接传感器
    import random
    return jsonify({
        'temperature': round(random.uniform(20, 35), 1),
        'speed': random.randint(0, 100),
        'time': time.strftime('%H:%M:%S')
    })

# ----------------- 控制接口 -----------------
@app.route('/move/<cmd>')
def move(cmd):
    # 先全部置低
    if cmd == 'forward':
        print('[ Info ] forward')
    elif cmd == 'backward':
        print('[ Info ] backward')
    elif cmd == 'left':
        print('[ Info ] left')
    elif cmd == 'right':
        print('[ Info ] right')
    elif cmd == 'stop':
        print('[ Info ] stop')
    return jsonify({'status': 'ok'})

@app.route('/device/<dev>/<action>')
def device(dev, action):
    if dev == 'buzzer':
        if action == 'on':
            print('[ Info ] fan on')
        elif action == 'off':
            print('[ Info ] fan off')
    elif dev == 'light':
        if action == 'on':
            print('[ Info ] light on')
        elif action == 'off':
            print('[ Info ] light off')

# ----------------- 主页 -----------------
@app.route('/')
def index():
    return render_template('index.html')

# ----------------- 主入口 -----------------
if __name__ == '__main__':
    # 启动摄像头线程

    try:
        app.run(host='0.0.0.0', port=5000, threaded=True)
    finally:
        print('[ Info ] Server stopped')